package main

import (
	"fmt"
	"net/http"
	"net/url"
	"os"
	"path"
	portainer "portainer_manager/src"
	"strconv"
	"strings"
	"time"

	"github.com/sirupsen/logrus"
)

var (
	GLOBAL_CONFIG             = new(portainer.Config)
	GLOBAL_RESTART_CONTAINERS = make([]*containerConfig, 0)
	GLOBAL_STOP_CONTAINERS    = make([]*containerConfig, 0)
	wxchatURL                 string
)

type containerConfig struct {
	EndPoint, ContainerName, ExecTime string
}

func init() {
	wxchatURL = os.Getenv("wxchatURL")

	tmp := os.Getenv("portainerURL")
	GLOBAL_CONFIG.Schema = "http"
	GLOBAL_CONFIG.Host = strings.Split(tmp, ":")[0]
	GLOBAL_CONFIG.Port, _ = strconv.Atoi(strings.Split(tmp, ":")[1])
	GLOBAL_CONFIG.User = "admin"
	GLOBAL_CONFIG.Password = "1"
	GLOBAL_CONFIG.URL = "/api"

	tmp = os.Getenv("restartDocker")
	for _, v := range strings.Split(tmp, ",") {
		fs := strings.Split(v, "|")
		GLOBAL_RESTART_CONTAINERS = append(GLOBAL_RESTART_CONTAINERS, &containerConfig{
			EndPoint:      fs[0],
			ContainerName: fs[1],
			ExecTime:      fs[2],
		})
	}
	tmp = os.Getenv("stopDocker")
	for _, v := range strings.Split(tmp, ",") {
		fs := strings.Split(v, "|")
		GLOBAL_STOP_CONTAINERS = append(GLOBAL_STOP_CONTAINERS, &containerConfig{
			EndPoint:      fs[0],
			ContainerName: fs[1],
			ExecTime:      fs[2],
		})
	}
}

func sendMsg(title, msg string) {
	logrus.Info(title, "→", msg)
	var form = make(url.Values)
	form.Add("msg", msg)
	// 标题用 ' 引起来避免包含空格 > < ( ) 等符号
	form.Add("title", fmt.Sprintf("'%s(%s)@%s'", title, path.Base(os.Args[0]), time.Now().Format("15:04:05")))
	_, err := http.PostForm(wxchatURL, form)
	if err != nil {
		logrus.Error("sendmsg error: ", err.Error())
	}
}
